const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

class OSUtils {
    constructor() {
        this.cpuUsageMSDefault = 1000; // CPU 利用率默认时间段
    }
    async getCPUUsage(options = {}) {
        const that = this;
        let cpuUsageMS = options.cpuUsageMS || 500
        let percentage
        if(options.percentage!=='undefined'){
            percentage = options.percentage
        }else{
            percentage = true
        }
        cpuUsageMS = cpuUsageMS || that.cpuUsageMSDefault;
        const t1 = that._getCPUInfo(); // t1 时间点 CPU 信息
        await sleep(cpuUsageMS);
        const t2 = that._getCPUInfo(); // t2 时间点 CPU 信息
        const idle = t2.idle - t1.idle;
        const total = t2.total - t1.total;
        let usage = 1 - idle / total;
        if (percentage) usage = (usage * 100.0).toFixed(2) + "%";
        return usage;
    }
    _getCPUInfo() {
        const cpus = os.cpus();
        let user = 0, nice = 0, sys = 0, idle = 0, irq = 0, total = 0;

        for (let cpu in cpus) {
            const times = cpus[cpu].times;
            user += times.user;
            nice += times.nice;
            sys += times.sys;
            idle += times.idle;
            irq += times.irq;
        }

        total += user + nice + sys + idle + irq;

        return {
            user,
            sys,
            idle,
            total,
        }
    }
}

let cpus = new OSUtils()


function get_cpu_usage(interval = 500, percentage = true) {
    return cpus.getCPUUsage(
        {
            cpuUsageMS: interval,
            percentage: percentage
        }
    )
}

function get_storage_usage() {
    let totalmem = os.totalmem() / 1024 / 1024
    let freemem = os.freemem() / 1024 / 1024
    let usedmem = totalmem - freemem
    return {
        totalmem,
        freemem,
        usedmem
    }
}

export default OSUtils
export {
    get_cpu_usage,
    get_storage_usage
}